package com.ahcloud.edas.gatewaylog.biz.infrastructure.log.client;

import com.ahcloud.edas.common.util.CollectionUtils;
import com.ahcloud.edas.gatewaylog.biz.domain.log.dto.GatewayRequestLogDTO;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @program: ahcloud-operatelog
 * @description:
 * @author: YuKai Fan
 * @create: 2024/5/26 21:24
 **/
@Slf4j
public abstract class AbstractLogConsumeClient<L extends GatewayRequestLogDTO> implements LogConsumeClient<L>{

    protected final AtomicBoolean isStarted = new AtomicBoolean(true);

    private final AtomicReference<Thread> closeThread = new AtomicReference<>();

    @Override
    public void initClient() {
        if (isStarted.get()) {
            this.close();
        }
        this.initClient0();
        isStarted.set(true);
        closeThread.set(new Thread(this::close));
        Runtime.getRuntime().addShutdownHook(closeThread.get());
    }

    @Override
    public void consume(List<L> logs) throws Exception {
        if (CollectionUtils.isEmpty(logs) || !isStarted.get()) {
            return;
        }
        this.consume0(logs);
    }

    @Override
    public void close() {
        if (Objects.nonNull(closeThread.get())) {
            Runtime.getRuntime().removeShutdownHook(closeThread.get());
        }
        if (isStarted.get()) {
            isStarted.set(false);
            try {
                this.close0();
            } catch (Exception e) {
                log.error("{} close error", this.getClass().getSimpleName());
            }
        }
    }

    /**
     * consume0.
     *
     * @param logs logs
     * @throws Exception error
     */
    public abstract void consume0(List<L> logs) throws Exception;

    /**
     * initClient0
     */
    protected abstract void initClient0();


    /**
     * close0
     * @throws Exception
     */
    protected abstract void close0() throws Exception;
}
